package com.eduadmin.listener;

import com.alibaba.excel.context.AnalysisContext;
import com.alibaba.excel.event.AnalysisEventListener;
import com.alibaba.excel.util.CollectionUtils;
import com.alibaba.fastjson.JSON;
import com.eduadmin.entity.Grade;
import com.eduadmin.service.IGradeService;
import lombok.extern.slf4j.Slf4j;

import java.util.ArrayList;
import java.util.List;

@Slf4j
public class GradeDataUploadListener extends AnalysisEventListener<Grade> {
    private int count = 1;
    private final IGradeService gradeService;

    public GradeDataUploadListener(IGradeService gradeService) {
        this.gradeService = gradeService;
    }

    List<Grade> list = new ArrayList<>();

    @Override
    public void invoke(Grade data, AnalysisContext context) {
        log.info("解析到一条数据:{}", JSON.toJSONString(data));
        Grade grade = gradeService.getGradeByGradeName(data.getGradeName());
        count++;
        if (grade == null) {
            list.add(data);
        } else {
            log.info("Excel表格中第 " + count + " 行 年级名称已经被使用，没有导入数据库！");
        }
        saveData();
        list.clear();
    }

    @Override
    public void doAfterAllAnalysed(AnalysisContext context) {
        //saveData();
        log.info("所有数据解析完成！");
    }


    private void saveData() {
        log.info("{}条数据，开始存储数据库！", list.size());
        if (!CollectionUtils.isEmpty(list)) {
            gradeService.addGrades(list);
        }
        log.info("存储数据库成功！");
    }


}
